package com.course.controller;

import com.course.assembler.UserSearchCourseAssembler;
import com.course.convert.StrToListFormatter;
import com.course.convert.StrToListStrFormatter;
import com.course.entity.dto.CourseDto;
import com.course.entity.dto.UserSearchDto;
import com.course.entity.vo.CourseVo;
import com.course.service.ICourseService;
import com.easyCode.feature.mybaits.CustomPage;
import com.easyCode.feature.result.ResponseResultAdvice;
import com.validator.RangeCheck;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.DataBinder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Positive;
import java.util.List;
import java.util.Map;

/**
 * @author zdh
 */
@Validated
@RestController
@RequestMapping("/course")
@RequiredArgsConstructor
@ResponseResultAdvice
@Api(tags = "课程请求")
public class CourseController {
    private final ICourseService iCourseService;
    private final UserSearchCourseAssembler userSearchCourseAssembler;

    @InitBinder
    public void initBinder(DataBinder dataBinder) {
        dataBinder.addCustomFormatter(new StrToListStrFormatter());
    }

    @ApiOperation("新增课程")
    @PostMapping("/save")
    public String saveCourse(@Validated CourseVo courseVo) {
        return iCourseService.saveCourse(courseVo);
    }

    @ApiOperation("检查课程是否上传成功")
    @PostMapping("/checkUpload")
    public Map<String, String> checkCourseUpload(@ApiParam("任务id列表,由' '分割任务id,如: 1 2 3") @RequestParam("taskId")List<String> taskId) {
        return iCourseService.checkCourseUpload(taskId);
    }

    @ApiOperation("根据id查询课程(普通管理员或者用户只能查询到自己所属校区下的课程)")
    @GetMapping("/{id}")
    public CourseDto getCourseById(@Positive(message = "id不合法")@PathVariable("id") Integer id) {
        return iCourseService.getCourseById(id);
    }

    @ApiOperation("分页批量查询课程(普通管理员或者用户只能查询到自己所属校区下的课程)")
    @GetMapping("/list")
    public List<CourseDto> listCourse(CustomPage customPage) {
        return iCourseService.listCourse(customPage);
    }

    @ApiOperation("课程上下架")
    @DeleteMapping("/enable/{id}")
    public void enableOrDisableCourse(@Positive(message = "id不合法")@PathVariable("id") Integer id,
                                      @RangeCheck(range = {1,0},message = "参数不合法")@RequestParam("enable")Integer enable) {
        iCourseService.enableOrDisableCourse(id,enable);
    }

    @ApiOperation("删除课程")
    @DeleteMapping("/{id}")
    public void delCourse(@Positive(message = "id不合法")@PathVariable("id") Integer id) {
        iCourseService.delCourseById(id);
    }

    @ApiOperation("分页批量查询课程(针对用户课程查询的特殊请求处理)")
    @GetMapping("/userList")
    public UserSearchDto userListCourse(CustomPage customPage) {
        return userSearchCourseAssembler.userListCourse(customPage);
    }
}
